import  io, re

f = open('bw.txt')
w = open('bw.xml', 'w')

w.write('<?xml version="1.0" encoding="iso-8859-1"?>')
w.write('<html>\n')
w.write('<meta http-equiv="Content-type" content="text/html;charset=ISO-8859-1" />')
w.write('<body>\n')

article = False
	
for line in f:
	line = line.replace('<', '&lt;').replace('>', '&gt;')
	line.replace('\n', '<br />')
	

	if line.startswith('  BOEK'):
		w.write(re.sub(r'  BOEK (\w*). - (.*).', r'<section><div class="1">\1</div><div>\2</div></section>', line))
		article = False
	elif line.startswith('INLEIDENDE TITEL'):
		w.write(re.sub(r'INLEIDENDE TITEL. - (.*)\.', r'<section><div class="2"></div><div>\1</div></section>', line)) 
		article = False
	elif line.startswith('  TITEL'):
		w.write(re.sub(r'  TITEL (\w*)\. - (.*)\.?', r'<section><div class="2">\1</div><div>\2</div></section>', line)) 
		article = False
	elif line.startswith('  HOOFDSTUK'):
		w.write(re.sub(r'  HOOFDSTUK (\w*)\. - (.*)\.?', r'<section><div class="3">\1</div><div>\2</div></section>', line)) 
		article = False
	elif line.startswith('  Afdeling'):
		w.write(re.sub(r'  Afdeling (\w*)\. - (.*)\.?', r'<section><div class="4">\1</div><div>\2</div></section>', line))
		article = False
	elif line.startswith('  AFDELING'):
		w.write(re.sub(r'  AFDELING (\w*)\. - (.*)\.?', r'<section><div class="4">\1</div><div>\2</div></section>', line))
		article = False
	elif line.startswith('  Onderafdeling'):
		w.write(re.sub(r'  Onderafdeling (\w*)\. - (.*)\.?', r'<section><div class="5">\1</div><div>\2</div></section>', line))
		article = False
	elif not(article) and re.match(r'  \xa7 \d+/?\d*\. [A-Z ]*', line):
		w.write(re.sub(r'  \xa7 ([\w/]*)\. (.*)\.?', r'<section><div class="5">\1</div><div>\2</div></section>', line)) 
		article = False
	elif not(article) and re.match(r'  [A-Z]\. ', line):
		w.write(re.sub(r'  ([A-Z])\. (.*)\.?', r'<section><div class="6">\1</div><div>\2</div></section>', line))
		article = False
	elif not(article) and re.match(r'  Artikel \d+\. ', line):
		w.write(re.sub(r'  Artikel (\d+)\. ?(.*)', r'<section><div class="7">\1</div><div>\2', line))
		article = True
	elif not(article) and re.match('  Art\. \d+\.$', line):
		w.write(re.sub(r'  Art\. (\d+)\.$', r'<section><div class="7">\1</div><div>', line))
		article = True
	elif not(article) and re.match('  Art\. \d+[\.\-]\d+\.', line):
		w.write(re.sub(r'  Art\. (\d+[\.\-]\d+)\.([ \xa7&\(\[].*)+', r'<section><div class="7">\1</div><div>\2', line)) 
		article = True
	elif not(article) and re.match('  Art\. \d+\w*\.([ \xa7&\(\[]*)', line):
		w.write(re.sub(r'  Art\. (\d+\w*)\.([ \xa7&\(\[]*)', r'<section><div class="7">\1</div><div>\2', line)) 
		article = True
	elif line.strip() == '':
		if article:
			w.write('</div></section>\n')
			article = False
	else:
		if article:
			if line.startswith('  '):
				w.write('<br />')
			w.write(line.strip())


f.close()

w.write('</body>\n')
w.write('</html>\n')
w.close()